interface Params {
    file: string;
    viewer: string;
    button: string;
    change: Function;
    success: Function;
}
interface FileObj {
    file: any;
    fileName: string;
}

class Easy_Upload {
    fileObj: FileObj;
    fileInput: HTMLInputElement | null;
    previewer: HTMLDivElement | null;
    send: HTMLButtonElement | null;
    constructor(obj: Params) {
        this.init(obj)
    }
    init(obj: Params) {
        if (Object.prototype.toString.call(obj) !== '[object Object]') {
            throw new Error("需传入一个object参数")
        } else {
            if (!obj.file || !obj.viewer || !obj.button) {
                throw new Error("参数不全")
            }
        }
        this.fileInput = document.querySelector(obj.file)
        this.previewer = document.querySelector(obj.viewer)
        this.send = document.querySelector(obj.button)
        if(this.fileInput && this.previewer && this.send){
            this.fileInput.onchange = (e) => { this.fileChange(e, obj) }
            this.send.onclick = () => { this.callback(obj) }
        }
        
    }
    fileChange(res: Event, obj: Params) {
        if(!this.fileInput || !this.previewer || !this.send || !this.fileInput.files){
            return
        }
        if (obj.change) {
            if (obj.change(res) == false) {
                return
            }
        }
        var _this = this
        var file = this.fileInput.files[0]
        var fileName = this.fileInput.files[0].name
        var img: HTMLImageElement = document.createElement("img")
        img.classList.add("Easy_Upload")
        this.previewer.innerHTML = ""
        this.previewer.appendChild(img)
        var reader = new FileReader()
        reader.onload = (function (aImg) {
            return function (e) {
                aImg.src = e.target.result
                _this.fileObj = {
                    file: e.target.result,
                    fileName
                }
            }
        })(img)
        reader.readAsDataURL(file)
    }
    dataURLtoFile(dataUrl, fileName) {
        var arr = dataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n); 1
        }
        return new File([u8arr], fileName, { type: mime });
    }
    callback(obj) {
        if (JSON.stringify(this.fileObj) == "{}") { return }
        let fileData = this.dataURLtoFile(this.fileObj.file, this.fileObj.fileName)
        if (obj.success) {
            obj.success({
                base64: this.fileObj.file,
                fileName: this.fileObj.fileName,
                file: fileData
            })
        }
    }
}